﻿using AutoMapper;
using HuiLian.Common.Input;
using HuiLian.Common.Output;
using HuiLian.Model.Platform;
using HuiLian.Repository.Platform;
using HuiLian.Service.Platform.CallTime.Input;
using HuiLian.Service.Platform.CallTime.Output;
using HuiLian.Service.Platform.CallTime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HuiLian.Repository.Platform.LoginCount;
using HuiLian.Service.Platform.LoginCount.Output;
using HuiLian.Service.Platform.LoginCount.Input;
using HuiLian.Common.Helpers;
using HuiLian.Common.Auth;

namespace HuiLian.Service.Platform.LoginCount
{
    /// <summary>
    /// 登录统计表服务
    /// </summary>
    public class LoginCountService : ILoginCountService
    {
        private readonly IMapper _mapper;
        private readonly ILoginCountRepository _loginCountRepository;

        public LoginCountService(IMapper mapper, ILoginCountRepository loginCountRepository)
        {
            _mapper = mapper;
            _loginCountRepository = loginCountRepository;
        }

        /// <summary>
        /// 获取指定用户Id的登录统计表信息
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="dateTime">年月</param>
        /// <returns></returns>
        public async Task<IResponseOutput<LoginCountEntity>> GetUserLoginAsync(long userId, DateTime dateTime)
        {
            ResponseOutput<LoginCountEntity> res = new ResponseOutput<LoginCountEntity>();
            var result = await _loginCountRepository.Select.Where(p => p.UserId == userId && p.MonthDate == dateTime).FirstAsync();
            return res.Ok(result);
        }

        /// <summary>
        /// 获取指定用户Id的登录统计表信息
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <returns></returns>
        public async Task<IResponseOutput> GetUserLoginCountAsync(long userId)
        {
            GetUserLoginCountOutput result = new GetUserLoginCountOutput();

            var count = await _loginCountRepository.Select.Where(p => p.UserId == userId).SumAsync(p => p.Count);
            result.TotalCount = (long)count;

            DateTime endYear = DateTime.Now.ToString("yyyy-12-01 00:00:00").ToDateTime();
            DateTime startYear = DateTime.Now.ToString("yyyy-01-01 00:00:00").ToDateTime();
            count = await _loginCountRepository.Select.Where(p => p.UserId == userId && p.MonthDate >= startYear && p.MonthDate <= endYear).SumAsync(p => p.Count);
            result.YearTotalCount = (long)count;

            DateTime month = DateTime.Now.ToString("yyyy-MM-01 00:00:00").ToDateTime();
            count = await _loginCountRepository.Select.Where(p => p.UserId == userId && p.MonthDate == month).SumAsync(p => p.Count);
            result.MonthTotalCount = (long)count;

            DateTime endDate = DateTime.Now.ToString("yyyy-MM-01 00:00:00").ToDateTime();
            DateTime startDate = endDate.AddYears(-1).AddMonths(1);
            var data = await _loginCountRepository.Select
                .Where(p => p.UserId == userId && p.MonthDate >= startDate && p.MonthDate <= endDate)
                .ToListAsync<LoginCountListOutput>();            
            for (DateTime date = DateTime.Now.ToString("yyyy-MM-01 00:00:00").ToDateTime().AddYears(-1).AddMonths(1); date <= endDate; date = date.AddMonths(1))
            {
                var monthData = data.Where(p => p.MonthDate == date).FirstOrDefault();
                if(monthData == null)
                {
                    LoginCountListOutput loginCountListOutput = new LoginCountListOutput()
                    {
                        Count = 0,
                        MonthDate = date,
                    };
                    data.Add(loginCountListOutput);
                }
            }
            data = data.OrderBy(p => p.MonthDate).ToList();
            result.MonthCountList = data;

            return ResponseOutput.Ok(result);
        }

        /// <summary>
        /// 获取登录统计表信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        public async Task<IResponseOutput> GetAsync(long id)
        {
            var result = await _loginCountRepository.GetAsync(id);
            return ResponseOutput.Ok(result);
        }

        /// <summary>
        /// 查询登录统计表信息
        /// </summary>
        /// <param name="input">分页信息</param>
        /// <returns></returns>
        public async Task<IResponseOutput> PageAsync(PageInput<LoginCountEntity> input)
        {
            //var key = input.Filter?.Label;

            var list = await _loginCountRepository.Select
            .WhereDynamicFilter(input.DynamicFilter)
            //.WhereIf(key.NotNull(), a => a.Path.Contains(key) || a.Label.Contains(key))
            .Count(out var total)
            .OrderByDescending(true, c => c.Id)
            .Page(input.CurrentPage, input.PageSize)
            .ToListAsync();

            var data = new PageOutput<LoginCountEntity>()
            {
                List = list,
                Total = total
            };

            return ResponseOutput.Ok(data);
        }

        /// <summary>
        /// 添加登录统计表信息
        /// </summary>
        /// <param name="input">登录统计表信息</param>
        /// <returns></returns>
        public async Task<IResponseOutput> AddAsync(LoginCountAddInput input)
        {
            var entity = _mapper.Map<LoginCountEntity>(input);
            var id = (await _loginCountRepository.InsertAsync(entity)).Id;

            return ResponseOutput.Result(id > 0);
        }

        /// <summary>
        /// 更新登录统计表信息
        /// </summary>
        /// <param name="input">登录统计表信息</param>
        /// <returns></returns>
        public async Task<IResponseOutput> UpdateAsync(LoginCountUpdateInput input)
        {
            if (!(input?.Id > 0))
            {
                return ResponseOutput.NotOk();
            }

            var entity = await _loginCountRepository.GetAsync(input.Id);
            if (!(entity?.Id > 0))
            {
                return ResponseOutput.NotOk("数据不存在！");
            }

            _mapper.Map(input, entity);
            await _loginCountRepository.UpdateAsync(entity);
            return ResponseOutput.Ok();
        }

        /// <summary>
        /// 更新登录统计表信息
        /// </summary>
        /// <param name="input">登录统计表信息</param>
        /// <returns></returns>
        public async Task<IResponseOutput> UpdateEntityAsync(LoginCountEntity input)
        {
            if (!(input?.Id > 0))
            {
                return ResponseOutput.NotOk();
            }

            var entity = await _loginCountRepository.GetAsync(input.Id);
            if (!(entity?.Id > 0))
            {
                return ResponseOutput.NotOk("数据不存在！");
            }

            entity.Count = input.Count;
            await _loginCountRepository.UpdateAsync(entity);
            return ResponseOutput.Ok();
        }
    }
}
